package com.jr.util;
// 数据库工具类


import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

@SuppressWarnings("all")
public class DBHelper {


    public Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.链接数据库
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "044614";
            con = DriverManager.getConnection(url, username, password);
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }
       return con;
    };

    public void closeAll(Connection conn, PreparedStatement ps, ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch(SQLException e){
            e.printStackTrace();
        }

    }

    //通用的增删改
    public int dtUpdate(String sql,Object... obj){
        Connection connection = getConnection();
        PreparedStatement ps = null;
        int count=0;
        try{
             ps=connection.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i+1,obj[i]);
            }
            count = ps.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            closeAll(connection,ps,null);
        }
        return count;
    }



    //通用查询方法
   public ArrayList dtQuery(String sql,Class cla, Object... obj){
        ArrayList list = new ArrayList();
        Connection con=getConnection();
       PreparedStatement ps=null;
       ResultSet rs=null;
        try{
            ps =con.prepareStatement(sql);
            for(int i=0;i<obj.length;i++){
                ps.setObject(i+1,obj[i]);
            }
           rs = ps.executeQuery();
            while(rs.next()){
                Object o = cla.newInstance();
                Field[] fileds = cla.getDeclaredFields();
                for(Field f:fileds){
                    f.setAccessible(true);
                    f.set(o,rs.getObject(f.getName()));
                }
                list.add(o);
            }
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch (InstantiationException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }
        finally{
            closeAll(con,ps,rs);
        }
        return list;
   }

}
